package com.tywj.panda.home

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.AnticipateOvershootInterpolator
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.autocareai.lib.extension.gone
import com.autocareai.lib.extension.visible
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.route.Route
import com.tywj.lib.route.RouteUtil
import com.tywj.navigation.city.ChooseCityActivity
import com.tywj.navigation.entity.CityEntity
import com.tywj.navigation.map.NavigationSelectedAddress
import com.tywj.navigation.tool.MapTool
import com.tywj.panda.customer.common.http.PDArrayCallback
import com.tywj.panda.customer.common.provider.INavigationService
import com.tywj.panda.customer.common.tool.LogoutTool
import com.tywj.panda.customer.common.tool.PermissionTool
import com.tywj.panda.customer.common.view.base.MyBaseFragment
import com.tywj.panda.home.api.HomeApi
import com.tywj.panda.home.entity.BannerEntity
import com.tywj.panda.home.entity.HomeLineEntity
import com.tywj.panda.home.entity.NoticeEntity
import com.tywj.panda.home.event.HomeEvent
import com.tywj.panda.home.miniprograme.MiniProgram
import com.tywj.panda.home.route.HomeRoute
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.home_banner_header_include.*
import kotlinx.android.synthetic.main.home_fragment_home.*
import kotlinx.android.synthetic.main.home_search_include.*


/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/05/18
 *     desc   : 首页
 *     version: 1.0.0
 * </pre>
 */
@Route(path = HomeRoute.HOME)
class HomeFragment : MyBaseFragment() {

    companion object {
        const val REQUEST_HOME_START = 2001
        const val REQUEST_HOME_END = 2002
        const val ANIMATION_DURATION = 500L
        const val REQUEST_CITY = 6000
    }

    private lateinit var footerApplyCourse: View
    private lateinit var viewApplyCourse: TextView

    //起点和终点
    private var startPoint = ""
    private var endPoint = ""

    // 起点poi
    private lateinit var startPoi: PoiItem

    // 终点poi
    private lateinit var endPoi: PoiItem

    //用于切换时的坐标处理
    private var startLng = 0.0
    private var startLat = 0.0
    private var endLng = 0.0
    private var endLat = 0.0

    //是否切换起点和终点
    private var isSwitch = false

    private var mAdapter = HomeLineAdapter()

    override fun getLayoutID(): Int = R.layout.home_fragment_home

    private lateinit var imageAdapter: HomeAdImageAdapter

    private var noticeEntity: NoticeEntity.DataBean? = null

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)
        // 这里对起点坐标虚构一个poi，方便处理
        startPoi = PoiItem(
            Int.MAX_VALUE.toString(), LatLonPoint(0.0, 0.0),
            ResourcesUtil.getString(com.tywj.navigation.R.string.navigation_my_location), ""
        )

        endPoi = PoiItem(
            Int.MAX_VALUE.toString(), LatLonPoint(0.0, 0.0),
            ResourcesUtil.getString(com.tywj.navigation.R.string.navigation_my_location), ""
        )
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        swipeRefreshLayout.setColorSchemeResources(R.color.common_yellow_FE)
        initRecyclerView()
    }


    override fun onVisibleEveryTime() {
        super.onVisibleEveryTime()

        activity?.let {
            BarUtil.setStatusBarColor(it, ResourcesUtil.getColor(R.color.common_yellow_FE))
            BarUtil.setStatusBarLightMode(it.window, true)
        }

        PermissionTool.location(requireActivity()) {}
    }

    override fun initListener() {
        super.initListener()

        ivDeleteStart.onClick {
            etStartPoint.setText("")

        }
        ivDeleteEnd.onClick {
            etEndPoint.setText("")
        }

        tvLocationCity.onClick {
            RouteUtil.getServiceProvider(INavigationService::class.java)
                ?.toSelectCity()?.navigation(this, REQUEST_CITY)
        }

        statusLayout.setOnEmptyLayoutButtonClick {
            // 重新加载数据
            loadDataLine()
            loadBanner()
            getBusFirstNotice()
        }

        statusLayout.setOnErrorLayoutButtonClick {
            // 重新加载数据
            loadDataLine()
            loadBanner()
            getBusFirstNotice()
        }

        swipeRefreshLayout.setOnRefreshListener {
            // 刷新首页数据
            loadDataLine()
            loadBanner()
            getBusFirstNotice()
        }

        ivMessage.onClick {
            HomeRoute.toNotice().navigation(requireActivity())

        }

        mAdapter.setOnItemChildClickListener { _, _, position ->
            val message = mAdapter.data[position]
        }

        ivSearch.onClick {

            startPoint = etStartPoint.text.trim().toString()
            endPoint = etEndPoint.text.trim().toString()

            loadDataLine()
        }

        ivSwitch.onClick {
            startPoint = etStartPoint.text.trim().toString()
            endPoint = etEndPoint.text.trim().toString()

            if (startPoint.isEmpty() || endPoint.isEmpty()) {
                shortToast("出发地或目的地不能为空")
                return@onClick
            }

            switchStartAndEndPoint()
        }

        etStartPoint.onClick {

            RouteUtil.getServiceProvider(INavigationService::class.java)
                ?.toSelectAddress(etStartPoint.text.toString(), INavigationService.FROM_START)
                ?.navigation(
                    this,
                    REQUEST_HOME_START
                )
        }

        etEndPoint.onClick {

            RouteUtil.getServiceProvider(INavigationService::class.java)?.toSelectAddress(
                etEndPoint.text.toString(),
                INavigationService.FROM_END
            )
                ?.navigation(
                    this,
                    REQUEST_HOME_END
                )
        }

        //到购买
        mAdapter.setOnItemChildClickListener { _, view, position ->

            val bean = mAdapter.data[position]
            when (view.id) {
                R.id.btnBuy -> {
                    LogoutTool.checkLoginStatus(requireActivity()) {
                        HomeRoute.toBuyTickets(lineCode = bean.lineInfoId, isFromHome = true).navigation(this)
                    }
                }
            }
        }
        //到线路详情-->购买
        mAdapter.setOnItemClickListener { _, _, position ->
            HomeRoute.toLineDetails(mAdapter.data[position]).navigation(this)
        }


        //申请线路
        viewApplyCourse.onClick {
            shortToast("开发中，敬请期待")
//            RouteUtil.getServiceProvider(INavigationService::class.java)?.toApplyCourse()?.navigation(this)
        }

        noticeMessage.onClick {

            noticeEntity?.let { bean ->
                HomeRoute.toNoticeDetail(bean, true).navigation(this)
            }
        }

        HomeEvent.refreshNoticeEvent.observe(this, Observer {
            gone(noticeMessage, viewMessageBg)
        })

    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()
        loadDataLine()

        loadBanner()

        getBusFirstNotice()

        //获取定位
        startGetMyCurrentLocation()
    }

    override fun onVisibleFirst() {
        super.onVisibleFirst()
//        IMConnect(AuthorityManager.rongyunToken)
    }

    private fun initRecyclerView() {

        recyclerView.adapter = mAdapter
        recyclerView.layoutManager = LinearLayoutManager(context)

        footerApplyCourse = layoutInflater.inflate(R.layout.home_footer_add_include, recyclerView, false)

        viewApplyCourse = footerApplyCourse.findViewById<TextView>(R.id.tvAddLine)

        mAdapter.addFooterView(footerApplyCourse)
    }


    private fun loadDataLine() {
        statusLayout.showLoadingLayout()

        if (isSwitch) {
            startLng = endPoi.latLonPoint.longitude
            startLat = endPoi.latLonPoint.latitude

            endLng = startPoi.latLonPoint.longitude
            endLat = startPoi.latLonPoint.latitude

        } else {

            startLng = startPoi.latLonPoint.longitude
            startLat = startPoi.latLonPoint.latitude

            endLng = endPoi.latLonPoint.longitude
            endLat = endPoi.latLonPoint.latitude
        }

        HomeApi.getBusLines(
            startLng = startLng,
            startLat = startLat,
            endLng = endLng,
            endLat = endLat
        ).attachToLifecycle(this)
            .execute(object : PDArrayCallback<HomeLineEntity.DataBean>(HomeLineEntity.DataBean::class.java) {
                override fun success(data: ArrayList<HomeLineEntity.DataBean>) {
                    statusLayout.showContentLayout()
                    handleData(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    statusLayout.showErrorLayoutByCode(code, message)
                }

                override fun onComplete() {
                    super.onComplete()

                    swipeRefreshLayout.isRefreshing = false
                }
            })
    }

    private fun loadBanner() {
        HomeApi.listBanner().attachToLifecycle(this)
            .execute(object : PDArrayCallback<BannerEntity>(BannerEntity::class.java) {
                override fun success(data: ArrayList<BannerEntity>) {
                    handleBannerData(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                }
            })
    }

    private fun handleBannerData(list: ArrayList<BannerEntity>) {
        imageAdapter = HomeAdImageAdapter(list)
        setBanner()
    }

    private fun handleData(data: ArrayList<HomeLineEntity.DataBean>) {
        mAdapter.setNewData(data)
        determineAddLine(data)
    }

    private fun setBanner() {

        adBanner?.let {
            it.addBannerLifecycleObserver(this)
            it.adapter = imageAdapter
            it.indicator = CircleIndicator(context)
            it.setIndicatorGravity(IndicatorConfig.Direction.CENTER)
            it.start()
        }

        //设置点击事件，下标是从0开始
        imageAdapter.setOnBannerListener { _, position ->
            val bean = imageAdapter.getData(position)
            //跳到小程序
            if (bean.path.isNotEmpty()) {
                MiniProgram.toMiniProgram(requireActivity(), bean.path)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_HOME_START -> {
                    val poi: PoiItem = data!!.getParcelableExtra(NavigationSelectedAddress.DATA_POI_ITEM)
                    updateStartPoint(poi)
                }
                REQUEST_HOME_END -> {
                    val poi: PoiItem = data!!.getParcelableExtra(NavigationSelectedAddress.DATA_POI_ITEM)
                    updateEndPoint(poi)
                }
                REQUEST_CITY -> {
                    val city: CityEntity = data!!.getParcelableExtra(ChooseCityActivity.PARAMS_CITY)
                    MapTool.CITY_CODE = city.cityCode

                    if (city.cityName.isNotEmpty()) {
                        tvLocationCity.text = city.cityName
                        MapTool.CITY_DEFAULT = city.cityName
                    }
                }
            }
        }
    }

    private fun updateStartPoint(poi: PoiItem) {
        if (poi.poiId == endPoi.poiId) {
            // 起点和终点不能相同
            shortToast(R.string.navigation_start_and_end_are_not_the_same)
            return
        }

        startPoi = poi

        etStartPoint.setText(poi.title)
        etStartPoint.setSelection(poi.title.length)
    }

    private fun updateEndPoint(poi: PoiItem) {

        if (poi.poiId == startPoi.poiId) {
            // 起点和终点不能相同
            shortToast(R.string.navigation_start_and_end_are_not_the_same)
            return
        }
        endPoi = poi

        etEndPoint.setText(poi.title)
        etEndPoint.setSelection(poi.title.length)
    }

    //得到当前位置
    private fun startGetMyCurrentLocation() {
        //获取当前位置
        var mLocationClient: AMapLocationClient? = null
        var mLocationOption: AMapLocationClientOption? = null
        //初始化定位
        mLocationClient = AMapLocationClient(context)

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener)

        mLocationOption = AMapLocationClientOption()
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption.isOnceLocation = true
        mLocationOption.isLocationCacheEnable = false //关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption)

        //启动定位
        mLocationClient.startLocation()
    }

    private var mLocationListener = AMapLocationListener { aMapLocation ->
        aMapLocation?.let {
            //我的位置
            etStartPoint.setText(it.poiName)
            tvLocationCity.text = it.poiName

            LogUtil.d("当前latitude：" + it.latitude + "longitude" + it.longitude)

            startPoi.latLonPoint.latitude = it.latitude
            startPoi.latLonPoint.longitude = it.longitude

            if (it.city.isNotEmpty()) {
                tvLocationCity.text = it.city
                MapTool.CITY_DEFAULT = it.city
                MapTool.CITY_CODE = it.cityCode
            } else {
                tvLocationCity.text = MapTool.CITY_DEFAULT
            }
        }
    }


    private fun switchStartAndEndPoint() {
        isSwitch = !isSwitch
        if (isSwitch) {
            etStartPoint.animate().translationYBy(etStartPoint.height.toFloat())
                .setDuration(ANIMATION_DURATION).interpolator =
                AnticipateOvershootInterpolator()

            etEndPoint.animate().translationYBy(-etEndPoint.height.toFloat())
                .setDuration(ANIMATION_DURATION).interpolator =
                AnticipateOvershootInterpolator()
        } else {
            etEndPoint.animate().translationYBy(etEndPoint.height.toFloat())
                .setDuration(ANIMATION_DURATION).interpolator =
                AnticipateOvershootInterpolator()

            etStartPoint.animate().translationYBy(-etStartPoint.height.toFloat())
                .setDuration(ANIMATION_DURATION).interpolator =
                AnticipateOvershootInterpolator()
        }

        val tempData = endPoint
        endPoint = startPoint
        startPoint = tempData
    }

    private fun determineAddLine(data: ArrayList<HomeLineEntity.DataBean>) {
        if (data.isEmpty()) {
            visible(footerApplyCourse)
        } else {
            gone(footerApplyCourse)
        }
    }

    /**
     * 获取发车提醒
     */
    private fun getBusFirstNotice() {
        HomeApi.homeNotice().attachToLifecycle(this)
            .execute(object : PDArrayCallback<NoticeEntity.DataBean>(NoticeEntity.DataBean::class.java) {
                override fun success(data: ArrayList<NoticeEntity.DataBean>) {
                    if (data.isEmpty()) return
                    //判断第一条数据是否已读，未读才滚动显示
                    noticeEntity = data.first()

                    if (noticeEntity?.read == 0) {
                        noticeMessage.text = noticeEntity?.content
                        noticeMessage.isSelected = true
                        visible(noticeMessage, viewMessageBg)

                    } else {
                        gone(noticeMessage, viewMessageBg)
                    }
                }
            })
    }
}